import React, { Component, createContext } from 'react'
import PropsTypes from 'prop-types'


const style = {
  box: {
    border: '1px solid #ddd',
    borderRadius: 10,
    padding: 15,
    margin: 15
  }
}

const AllContext = createContext() // 全局的 context 对象

export default class MyContext extends Component {

  // 定义子组件的 context 数据
  getChildContext() {
    return {
      msg: '我等的模样好不具象,用皮肤感受你的流向',
      count: 4090
    }
  }

  state = {
    word: '我好像在哪见过你'
  }

  render() {
    return (
      <div>
        <h3>MyContext - 隔空传递 - 时空穿梭</h3>
        {/* <CptA word={this.state.word}></CptA> */}
        <MyParent></MyParent>
      </div>
    )
  }
}

const value = {
  word: '我好像在哪见过你',
  tips: '你不就像风一样',
  time: '2023.3.10',
  message: '和风一样'
}

class MyParent extends Component {
  render() {
    return (
      <div>
        <AllContext.Provider value={value}>
          <Middle></Middle>
        </AllContext.Provider>
      </div>
    )
  }
}

// 中间组件
class Middle extends Component {
  render() {
    return (
      <Two></Two>
    )
  }
}

// 获取 context 
class Two extends Component {
  static contextType = AllContext
  render() {
    return (
      <div>
        <CptA></CptA>
      </div>
    )
  }
}

MyContext.childContextTypes = {
  msg: PropsTypes.string.isRequired,
  count: PropsTypes.number,
  word: PropsTypes.string
}


class CptA extends Component {
  render() {
    return (
      <div style={style.box}>
        <h3>组件A - 1</h3>
        <CptB word={this.props.word}></CptB>
      </div>
    )
  }
}

class CptB extends Component {
  static contextType = AllContext
  render() {
    return (
      <div style={style.box}>
        <h3>组件B - 2</h3>
        <h4>tips = {this.context.tips}</h4>
        <h4>time = {this.context.time}</h4>
        <h4>message = {this.context.message}</h4>

        <CptC word={this.props.word}></CptC>
      </div>
    )
  }
}

class CptC extends Component {
  render() {
    return (
      <div style={style.box}>
        <h3>组件C - 3</h3>
        <h4>count = {this.context.count}</h4>
        <CptD word={this.props.word}></CptD>
      </div>
    )
  }
}

CptC.contextTypes = {
  count: PropsTypes.number
}


class CptD extends Component {
  static contextType = AllContext
  render() {
    // const { word } = this.props
  // const { msg } = this.context
  return(
  <div style = { style.box } >
    <h3>组件D - 4</h3>
    <h4>word = {this.context.word}</h4>
    {/* <h4>msg = {msg}</h4> */}
  </div>
)
  }
}

// CptD.contextTypes = {
//   word: PropsTypes.string,
//   msg: PropsTypes.string
// }
